package binary.reader

import binary.FtTag
import binary.ValType
import binary.panic
import binary.type.FuncType

fun WasmReader.readTypeSec(): Array<FuncType?> {
    val vec = arrayOfNulls<FuncType>(ReadVarU32().toInt())
    for (i in vec.indices) {
        vec[i] = ReadFuncType()
    }
    return vec
}
// entity types
fun WasmReader.ReadFuncType(): FuncType {
    val ft = FuncType(
        Tag = ReadByte(),
        ParamTypes = readValTypes(),
        ResultTypes = readValTypes()
    )

    if (ft.Tag != FtTag.toByte()) {
        panic("invalid functype tag: ${ft.Tag}")
    }

    return ft
}

// value types
fun WasmReader.readValTypes(): Array<ValType?> {
    val vec = arrayOfNulls<ValType>(ReadVarU32().toInt())
    for (i in vec.indices) {
        vec[i] = readValType()
    }
    return vec
}

fun WasmReader.readValType(): ValType? {
    val vt = ValType.get(ReadByte())
    when (vt) {
        ValType.ValTypeI32, ValType.ValTypeI64, ValType.ValTypeF32, ValType.ValTypeF64 -> return vt
        else -> vt?.let { panic("malformed value type: $it") }
    }
    return vt
}